// pages/booK_detail/book_detail.js
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        
        home_id: "", //从首页中拿到的书籍id
        //我觉得要有三个数组
        //第一个数组装载书籍本身信息BookInfo
        BookInfo:"",
        //第二个数组装载书籍售卖信息BookSellInfo
        BookSellInfo:"",
        //第三个数组展示书籍外貌信息fileList
        fileList:"",
        //我觉得可以添加一个相似推荐More
        id:"",
        currentIndex: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options){
      const that=this
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.on('bookData', function (data) {
        that.setData({
          fileList:data.childArray
        })
      });
     
      eventChannel.on('id', function (data) {
        that.getBookSellInfo(data.id)
        that.setData({
          id:data.id
        })
      });
      //图片补偿
      // this.picture_compensate()
    },
    previewImage: function(event) {
      const currentUrl = event.currentTarget.dataset.src;
      const urls = this.data.fileList;
      wx.previewImage({
        current: currentUrl,
        urls: urls
      });
    },
    //图片补偿
    picture_compensate: function () {
      const that = this;
      const ctx = wx.createCanvasContext('myCanvas');
      const url = that.data.fileList[that.data.currentIndex];
  
      wx.getImageInfo({
        src: url,
        success: function (res) {
          ctx.drawImage(res.path, 0, 0, 400, 300);
          ctx.filter = 'blur(0.8)';
          ctx.draw(false, () => {
            wx.canvasToTempFilePath({
              canvasId: 'myCanvas',
              success: function (res) {
                that.setData({
                  currentIndex: (that.data.currentIndex + 1) % that.data.fileList.length
                });
                setTimeout(that.picture_compensate.bind(that), 3000);
              },
              fail: function (res) {
                console.error('canvasToTempFilePath failed:', res);
              }
            });
          });
        },
        fail: function (res) {
          console.error('getImageInfo failed:', res);
        }
      });
    },
    
    


    async getBookSellInfo(id){
      const booksellinfo=await wx.p.request({
        url: app.globalData.url+"/book_detail/getBookSellInfo",
        method:"GET",
        data:{
          id:id
        }
      })
      console.log(booksellinfo)
      this.setData({
        BookSellInfo:booksellinfo.data.data[0]
      });
      this.getBookInfo(this.data.BookSellInfo.isbn);
    },
    async getBookInfo(isbn){
      const bookinfo=await wx.p.request({
        url: app.globalData.url+"/book_detail/getBookInfo",
        method:"GET",
        data:{
          isbn:isbn
        }
      })
      console.log(isbn)
      this.setData({
        BookInfo:bookinfo.data.data[0]
      })
    },
    // async getfileList(fileUrl) {
    //   const response = await wx.p.request({
    //     url: app.globalData.url + "/book_detail/getfileList",
    //     method: "GET",
    //     data: {
    //       url: fileUrl
    //     }
    //   });
    //   this.setData({
    //     fileList:  response.data.data
    //   });
    // },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },


    //点击加入购物车操作
    // 1 判断该书籍是否存在，存在的话num+1
    // 2 把对应的书籍数据以及用户openid一起传入云数据库中
    //加入购物车
    addcart() {
        
        var that = this
        var cart={
          img:that.data.BookInfo.img,
          title:that.data.BookInfo.title,
          price:that.data.BookSellInfo.price,
          num:1,
          select: 'circle',
          isTouchMove:false
        }
        wx.getStorage({
          key: 'cartList',
          success(res) {
            const cartList = res.data || [];
            const existingItemIndex = cartList.findIndex(item => item.key === that.data.id);
            if (existingItemIndex !== -1) {
              wx.showToast({
                title: '该商品已在购物车中',
                icon: 'none'
              });
            } else {
              cartList.push({ key: that.data.id, data: cart });
              wx.setStorage({
                key: 'cartList',
                data: cartList,
                success() {
                  wx.showToast({
                    title: '已加入购物车',
                    icon: 'success'
                  });
                }
              });
            }
          },
          fail() {
            const cartList = [{ key: that.data.id, data: cart }];
            wx.setStorage({
              key: 'cartList',
              data: cartList,
              success() {
                wx.showToast({
                  title: '已加入购物车',
                  icon: 'success'
                });
              }
            });
          }
        });
      },

    //点击转跳购物车
    goToshoppingcart: function () {
        wx.switchTab({
            url: '../shopping_cart/cart',
            success: function (res) {},
            fail: function () {},
            complete: function () {}
        })
    },
    

})